﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Cors;
using BSF.Attributes;
using HuntingFishGame.OpenApi;
using HuntingFishGame.OpenApi.Extensions;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace HuntingFishGame.CustomerApi
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务
            // 将 Web API 配置为仅使用不记名令牌身份验证。
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API 路由
            config.MapHttpAttributeRoutes();
            //跨域配置
            //config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            config.EnableCors();
            config.SetCorsPolicyProviderFactory(new DynamicPolicyProviderFactory(new string[] { "*" }));

            //C#进阶系列——WebApi 跨域问题解决方案：CORS http://www.cnblogs.com/landeanfen/p/5177176.html
            ////System.Web.Http.Cors配置跨域访问的两种方式 http://blog.csdn.net/chaoyangzhixue/article/details/52251322
            //EnableCors共三个参数分别为origins、headers和methods。origins配置允许访问的域名，多个域名以逗号分隔即可，域名一定要完整，如果是ip地址前面要加上“http”，只使用IP的话一定会失效的。参数headers配置所支持的资源。参数methods配置支持的方法，get、post、put等。如果允许任意域名、任意资源、任意方法访问自己的webapi，则三个参数全部使用星号”*”即可。
            //“EnableCors(“http://localhost:9012,http://192.168.1.108:9012“, ““, ““)”中的配置如果出现错误的话不会报错，而是直接禁止未出现在配置表中的资源访问。
            //如果使用第一种方式那么可以从配置文件中读取网站列表，如果使用第二种方式，所有的参数只能使用常量。

            ////从配置文件的appsettings节点中读取跨域的地址
            //var cors = new EnableCorsAttribute(ConfigurationManager.AppSettings["origins"], "*", "*");
            //config.EnableCors(cors);

            config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);


            config.Formatters.Remove(config.Formatters.XmlFormatter);
            //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            //config.Formatters.Add(new BrowserJsonFormatter());

            config.Filters.Add(new DbContextFilter());
            config.Filters.Add(new TimingActionFilter());
            config.Filters.Add(new ValidSignatureAttribute(true));//校验签名
            //config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());
            //config.Services.Replace(typeof(IExceptionLogger), new GlobalExceptionLogger());

            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;


            var serializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
            serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            var contractResolver = (DefaultContractResolver)serializerSettings.ContractResolver;
            contractResolver.IgnoreSerializableAttribute = true;


            //json.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All;
            json.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });

            //注册Exceptionless异常相关
            //ExceptionlessClient.Default.RegisterWebApi(config);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class BrowserJsonFormatter : JsonMediaTypeFormatter
    {
        /// <summary>
        /// 
        /// </summary>
        public BrowserJsonFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
            //this.SerializerSettings.Formatting = Formatting.Indented;
        }

        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);
            headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    }
}
